<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>SDK Data Manager Demo</title>
		<style>
			/*reset and common*/
			body,div,ul,ol,li,h1,h2,h3,h4,h5,h6,form,input,button,textarea,p,th,td{margin:0;padding:0;}
			table{border-collapse:collapse;border-spacing:0;}
			img{border:0;}
			li{list-style:none;}
			em{font-style:normal;}
			html,body{font:normal 11px Verdana,Arial,Helvetica,sans-serif;background:#fff;color:#333;height:100%;}
			h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}
			input,button,textarea,select,optgroup,option{font-family:inherit;font-size:inherit;font-style:inherit;font-weight:inherit;background:#fff;}
			input,button,textarea,select{*font-size:100%;}
			input{vertical-align:middle;}
			a{color:#333;text-decoration:none;}
			p{line-height:1.6;}
			.clearfix{zoom:1;} 
			.clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden;font-size:0;}
			h2,h3,h4,h5{font-weight:bold;}

			.sdk-datamanager-widget-container{
				border: 1px solid #CCCCCC;
				width: 600px;
				padding-top:5px;
				padding-bottom:5px;
				padding-left:5px;
				padding-right:5px;
				margin-top:5px;
				margin-left:5px;
			}
			.sdk-datamanager-demo .sdk-datamanager-title {
				background: none repeat scroll 0 0 #F6F6F6;
				color: #006595;
				padding: 7px 0 7px 5px;
				font-weight:bold;
			}
			.sdk-datamanager-toolContainer{
				background: none repeat scroll 0 0 #F0F0F0;
				border: 1px solid #CCCCCC;
				height: 150px;
				padding-top:5px;
				margin-bottom: 5px;				
			}
			.sdk-datamanager-toolContainer .server-input{
				width:200px;
			}
			
			.sdk-datamanager-toolContainer .cell{
				margin-left:15px;
				float:left;	
			}
			.sdk-datamanager-toolContainer .cell-over{
				clear:both
			}				
			.sdk-datamanager-toolContainer .symbol-selector{
				width:150px;
				height:100px;
			}
			
			.sdk-datamanager-toolContainer .hidden{
				display:none;
			}			
			.sdk-datamanager-widget-container .stock-table{
				margin-top:5px;
			}
			.sdk-datamanager-widget-container .stock-table .font-red{
				color:#FF0000;
			}	
			.sdk-datamanager-widget-container .stock-table .font-green{
				color:#00FF00;
			}
			.sdk-datamanager-widget-container .stock-table .font-black{
				color:#000000;
			}			
			.sdk-datamanager-widget-container .stock-title{
				background: none repeat scroll 0 0 #F6F6F6;
			}
			.sdk-datamanager-widget-container .widget-id{
				margin-left:30px;
			}
			.sdk-datamanager-widget-container .stock-table td{
				border: 1px solid #CCCCCC;
			}
			.sdk-datamanager-widget-container .fieldset{
				height:150px;
			}
			.sdk-datamanager-widget-container .radioContainer{
				margin-left:20px;
			}

			
		</style>

	<!--jquery-->
	<script type="text/javascript" src="../../../lib/jquery.js"></script>
	<!--core-->
	<script type="text/javascript" src="../../../lib/jquery.mousewheel.js"></script>
	<script type="text/javascript" src="../../../lib/jquery.json.min.js"></script>
	<script type="text/javascript" src="../../../core/common.js"></script>
	<script type="text/javascript" src="../../../core/permissionChecker.js"></script>
	<script type="text/javascript" src="../../../core/tickers.js"></script>
	<script type="text/javascript" src="../../../core/subscriber.js"></script>
	<script type="text/javascript" src="../../../core/dataHandler.js"></script>
	<script type="text/javascript" src="../../../core/pull.js"></script>
	<script type="text/javascript" src="../../../core/push.js"></script>
	<script type="text/javascript" src="../../../core/SDKDataManager.js"></script>
	<script>
		var connected=false;
		var connectType='pull',iSelRadio=0;
		var widgets=[];
		
		function removeAllWidgets(){
			for(var i=0;i<widgets.length;i++){
				widgets[i].unsubscribe();
				widgets[i].remove();
				widgets[i]=null;
				widgets.pop(i);
			}
		}
		function disconnect(){
			if (!connected){
				return;
			}
			var status=$("#lblStatus");
			if (connectType=='push'){
				 QSAPI.DataManager.disconnectPush();			//No callback
			}else{
				 QSAPI.DataManager.disconnectPull();			//No callback
			}
			status.text("Not Connect");
			$("#btnConnect").show();
			$("#btnDisconnect").hide();		
			connected=false;
		}
	
		$(document.body).ready(function(e){	
			$("#btnDisconnect").hide();	
			 //document.getElementById("radSwitchConnectType1").click();
			 iSelRadio=2;
			 QSAPI.init('DISN');			
			 QSAPI.Authentication.login("511F1BFFABACF2797D53014B7B7EF29F502E7015781E8D93A04989A70197E422B9AC0FE2E59882CDC9713E118EEA680F7F0E859C73FBD6BEF64C7DD04490EF1A","62D2A0641B01FBF65FA127365CDC0DC427458A67D958FC979718FF067CCD1A8D8D4E839255D60957C1A502D25C724A1D65F6EEE07636A0AA84E8F51C8D1831EE",{
				onFailure:function(result){
					$("#logStatus").text(result.errorMessage);
				},
				onSuccess:function(result){
					$("#logStatus").text(result.errorMessage);
				}
			});
	
		/*
			Push
		*/
		$("#radSwitchConnectType1").click(function(){
			if (iSelRadio!=1){
				disconnect();
				removeAllWidgets();
			}
			connectType='push';
			$("#containerForPush").show();
			$("#containerForPull").hide();
			iSelRadio=1;
		});
		
		/*
			pull
		*/
		$("#radSwitchConnectType2").click(function(){
			if (iSelRadio!=2){
				disconnect();	
				removeAllWidgets();
			}			
			connectType='pull';					
			$("#containerForPush").hide();
			$("#containerForPull").show();
			iSelRadio=2;
		});		
		
		/*
			disconnect
		*/
		$("#btnDisconnect").click(function(){	
			disconnect();
		});
		
		/*
			connect
		*/		
		$("#btnConnect").click(function(){	
			var status=$("#lblStatus");
			status.text("Connecting...");
			if (connectType=='push'){			
			 QSAPI.DataManager.connectToPush($("#txtServerPush").val(),{
                         onFailure:function(eventType,err){							
                             status.text(err);
							 status.css('color','red');
							 connected=false;
							 $("#btnDisconnect").hide();
							 $("#btnConnect").show();
                         },
                         onSuccess:function(eventType){
                            status.text("Connected");
							connected=true;
							status.css('color','black');
							$("#btnConnect").hide();
							$("#btnDisconnect").show();
						}
            });	
			}else{
			
			 QSAPI.DataManager.connectToPull($("#txtServerPull").val(),$("#txtServerPullFrequency").val(),{
                         onFailure:function(eventType,err){							
                             status.text(err);
							 status.css('color','red');
							 connected=false;
							 $("#btnDisconnect").hide();
							 $("#btnConnect").show();
                         },
                         onSuccess:function(eventType){
                            status.text("Connected");
							connected=true;
							status.css('color','black');
							$("#btnConnect").hide();
							$("#btnDisconnect").show();
						}
            });				
			}
		});		
		
		$("#btnAddWidget").click(function(){
			var selector=$('.sdk-datamanager-toolContainer .symbol-selector');
			if (selector.val()){
				var container=new Example.Widget($("body"));
				widgets.push(container);
				for(var i=0;i<selector.val().length;i++){					
					var option=$(selector.find("option[value='"+selector.val()[i]+"']"));
					container.addStock(
						new Example.Stock(
							{
								title:option.val()+':'+option.text(),
								tickerKey:option.val()
							}
						)
					);
				}			
			}
		});
	});
	</script>			
		
	<script>
		/*Example Page Starte
		*/
	if (!Example){
		var Example={};
	}
		/*Widget*/
	Example.Widget=function(container,config){
		var radStr=this._getRandom(10);
		this.config={
				id:'ExampleWidget_'+radStr,
				title:'',
				radStr:radStr
		}
		$.extend(this.config,config);

		this.HTML='<div id="'+this.config.id+'" class="sdk-datamanager-widget-container">'+
					'<div>'+
						'<input type="button" value="Subscribe" name="btnSubscrible">'+
						'<input type="button" value="Stop" name="btnStop">'+
						'<input type="button" value="Remove Widget" name="btnRemove">'+
						'<label class="widget-id">WidgetID:'+this.config.id+'</label>'+
					'</div>'+
				  '</div>';
		this.Stocks=[];		
		this.init(container);		
	};
			
	Example.Widget.prototype={
		init:function(container){
			var self=this;
			var config=this.config;	
			this.dataComponent={
					subscribeID:'com_'+config.radStr,
					updateData:function(tickerObj, data){
						self.updateData(tickerObj,data);
					}
			}
			this.el = $(this.HTML);
			$(container).append(this.el);
			this.el.find("input[name='btnSubscrible']").bind("click",function(){
				self.subscribe();	
			});
			this.el.find("input[name='btnStop']").bind("click",function(){
				self.unsubscribe();	
			});
			this.el.find("input[name='btnRemove']").bind("click",function(){
				self.remove();	
			});	
			this.accessType=connectType;
		},
		setAccessType:function(accessType){
			this.unsubscribe();
			for(var i=0;i<this.Stocks.length;i++){				
				this.Stocks[i].setAccessType(accessType);
			}
		},
		addStock:function(stock){
			stock.appendTo(this.el);
			this.Stocks.push(stock);
		},
		updateData:function(tickerObj,data){
			for(var i=0;i<this.Stocks.length;i++){
				var pid=this.Stocks[i].getTickerKey();
				if (pid==tickerObj.getField("performanceId")){
					this.Stocks[i].update(data);
					break;
				}
			}
		},
		subscribe:function(){
			var self=this;
			var keys=[];
			for(var i=0;i<this.Stocks.length;i++){
				var key=this.Stocks[i].getTickerKey();
				keys.push(key);
			}
			QSAPI.TickerFactory.create(keys,{
				onSuccess:function(tickerObjects){
					if (self.accessType=='push'){
						QSAPI.DataManager.subscribePush(self.dataComponent,tickerObjects);
					}else{
						QSAPI.DataManager.subscribePull(self.dataComponent,tickerObjects);
					}
				}
			});
		},
		unsubscribe:function(){	
			var self=this;		
			var keys=[];
			for(var i=0;i<this.Stocks.length;i++){
				var key=this.Stocks[i].getTickerKey();
				keys.push(key);
			}
			QSAPI.TickerFactory.create(keys,{
				onSuccess:function(tickerObjects){
					if (self.accessType=='push'){
						QSAPI.DataManager.unSubscribePush(self.dataComponent,tickerObjects);
					}else{
						QSAPI.DataManager.unSubscribePull(self.dataComponent,tickerObjects);
					}
				}
			});
		},
		remove:function(){
			QSAPI.DataManager.deregisterComponent(this.dataComponent);
			this.el.remove();
		},
		_getRandom:function(n){
			var chars = ['0','1','2','3','4','5','6','7','8','9'];
			var res = "";
			for(var i = 0; i < n ; i ++) {
				var id = Math.ceil(Math.random()*9);
				res += chars[id];
			}
			return res;								
		}		
};			
		
		/*Stock*/
	Example.Stock=function(config){
		this.config={
			title:'',
			tickerKey:'XNYS:IBM',
			viewKeys:["LastPrice","AskPrice","AskSize","BidPrice","BidSize","Chg","Chg%","ClosePrice","HighPrice"],
			cols:4
		};
		$.extend(this.config,config);			
		if (this.config.cols<=2){
			this.config.cols=4;
		}
		this.HTML='<table class="stock-table" border=1 style="border-collapse:collapse">'+
					'<tr>'+
					'<td colspan="'+this.config.cols+'" class="tickerKey stock-title">'+this.config.title+'</td>'+
					'</tr>'+
					'</table>';
		this.init();
	};
	this.accessType='pull';
		

		
	Example.Stock.prototype={
		init:function(){
		var config=this.config;
		this.el = $(this.HTML);	
		var row=null;
		for (var i=0;i<config.viewKeys.length;i++){					
			if (i%config.cols==0){
				row=this._addRow();
				this.el.append(row);
			}
			this._addCell(row,config.viewKeys[i]);
		}
		
		},
		getTickerKey:function(){
			return this.config.tickerKey;
		},
		setAccessType:function(accessType){
			this.accessType=accessType;
		},		
		update:function(data){
			for (var i=0;i<this.config.viewKeys.length;i++){
				var viewKey=this.config.viewKeys[i];
				this._updateCell(viewKey,data);
			}
		},
		appendTo:function(container){
			this.el.appendTo($(container));
		},
		_addRow:function(){
			var row=$('<tr></tr>');
			return row;
		},
		_updateCell:function(key,data){
			var obj=data[key];
			if (typeof(obj)=='undefined'){
				return;
			}
			var targetElm=this.el.find('.'+this._replaceSpecialCharacter(key));
			targetElm.css('background-color','');
			if (obj.oValue && obj.oValue>obj.value){
				targetElm.addClass('font-red');
			}else if (obj.oValue && obj.oValue==obj.value){
				targetElm.addClass('font-black');
			}else if (obj.oValue && obj.oValue<obj.value){
				targetElm.addClass('font-green');
			}else{			
				targetElm.addClass('font-black');
			}
			
			targetElm.text(obj.dataType=='f'?obj.value.toFixed(2):obj.value);
		},
		_addCell:function(row,viewKey){
			var cell=$('<td></td>');				
			var span=$('<span>'+viewKey+':</span><span class="'+this._replaceSpecialCharacter(viewKey)+'"></span>');
			span.appendTo(cell);
			cell.appendTo(row);
			cell.width(200);
		},
		_replaceSpecialCharacter:function(str){
			return str.replace(/\%/,'_percent');
		}
	}
	</script>			
	</head>
    <body>
	<div class="sdk-datamanager-demo">
		<div id="aaaa"></div>
		<div id="tickerListContainer"></div>
		
		<h1 class="sdk-datamanager-title">Push Data</h1>
		<div class="sdk-datamanager-toolContainer">
			<div class="cell">
				<fieldset style="height:125px">
					<div>
						<label>Access Type:</label>
						<input type="radio" name="radSwitchConnectType" id="radSwitchConnectType1"/><label id="lblForRadio1">Push</label>
						<input type="radio" name="radSwitchConnectType" id="radSwitchConnectType2" checked="checked"/><label id="lblForRadio2">Pull</label>				
					</div>
					<br/>
				<div id="containerForPull" >
					<div>
						<label>Frequency(ms):</label>
						<input type="text" class="server-input" style="width:100px" id="txtServerPullFrequency" value="5000"/>
					</div>
					<br/>
					<div>
						<label>Data Server:</label>
						<input type="text" class="server-input" id="txtServerPull" value="http://qsstage.morningstar.com/pullservice/pull/getPullQuote.jsp"/>
					</div>					
				</div>
				<div id="containerForPush" class="hidden">
					<div>
						<label>Data Server:</label>
						<input type="text" class="server-input" id="txtServerPush" value="http://push.morningstar.com"/>
					</div>
				</div>
				<br/>
					<div>
						<input type="button" id="btnConnect" value="Connect" title="Connect to server"/>
						<input type="button" id="btnDisconnect" value="Disconnect" title="Disconnect server"/>
						<label><span>Status:</span><span id="lblStatus">Not Connect</span></label>
					</div>
				</fieldset>
			</div>
			<div class="cell">
				<fieldset style="height:125px">
				<select multiple class="symbol-selector">				
					<option value="0P000003MH">MSFT</option>
					<option value="0P000002RH">IBM</option>
					<option value="0P000003PE">MORN</option>
					<option value="0P00009KJ4">FB</option>
					<option value="0P0000TUGF">ORAC</option>
					<option value="0P0000AWO7">YHO</option>	
					<option value="0P00000002">CTAC</option>				
				</select>
				<br/>
				<input type="button" id="btnAddWidget" value="Add Widget"/>
				</fieldset>
			</div>
			<div class="cell">
				<fieldset style="height:125px">
					<label>Authentication Status:</label>
					<br/>
					<label id="logStatus">Not Login</label>					
				</fieldset>
			</div>			
			<div class="cell-over"></div>
		</div>
		<div id="widgetsContainer"></div>
	</div>
	</body>
</html>

